#include "Controller.h"
#include "..\Infobus\ComponentRegister.h"
#include "..\Infobus\Infobus.h"
#include "..\Infobus\Types.h"
#include "..\Infobus\XmlHelper.h"
#include "..\Infobus\DatabaseAdapter.h"
#include "..\Infobus\EventHandler.h"
#include "..\Infobus\ActionHandler.h"
#include "..\Infobus\MetaXmlHandler.h"
#include <sstream>

Controller::Controller()
: ControllerBase()
{
  CoInitialize(NULL);
}

void Controller::onMessage(const char * m)
{  
  if (m) {
    std::stringstream ss;
    ss << m << std::endl;

    if (ControllerBase::isMaster()) {
      long lMsgId = 0, lLastLogID = 0;   
      Action * pAction = NULL;
      EventHandler * evthnd = new EventHandler;
      ActionHandler * acthnd = new ActionHandler;
      MetaXmlHandler xmlhnd(m);

      evthnd->SelectMsgId(m, &lMsgId);      
      acthnd->SelectActionData(m, &pAction);
      acthnd->StoreActionForLog(pAction);
      lLastLogID = acthnd->getLastLogIdForLog();
      acthnd->StoreActionProcedureForLog(lLastLogID, pAction->getActionName(), pAction->getSteps());
      
      std::list<Trace*> liTraces;
      xmlhnd.getActionTraces(liTraces);
      acthnd->StoreActionTraceForLog(lLastLogID, pAction->getActionName(), liTraces);

      if (evthnd) delete evthnd;
      if (acthnd) delete acthnd;
      if (pAction) delete pAction;
    }
  }
}

